package com.bdth.weget.net.codec;

import com.bdth.weget.net.base.ConstantValue;
import com.bdth.weget.util.BinaryUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by Administrator on 2018/4/18.
 */
public class ProtocolEncoder extends MessageToByteEncoder<byte[]> {



    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, byte[] s, ByteBuf byteBuf) throws Exception {
        byte[] send = null;
        if(s[0]== ConstantValue.HEAD_DATA && s[s.length-1]== ConstantValue.END_DATA) {
            byte[] b = new byte[s.length-2];
            for (int i = 1; i < s.length - 1; i++) {
                b[i-1] = s[i];
            }
            byte[] temp = BinaryUtil.Escape(b);
            send = new byte[temp.length+2];
            send[0] = ConstantValue.HEAD_DATA;
            for(int i=1;i<send.length-1;i++){
                send[i] = temp[i-1];
            }
            send[send.length-1] = ConstantValue.END_DATA;

        }
        byteBuf.writeBytes(send);
    }
}
